package com.romotc.qqrobot.config;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.DeserializerFactory.Config;

import com.romotc.json.tools.Jackson;
import com.romotc.qqrobot.config.bean.QQUrlWatcherConfig;
import com.romotc.scache.httpreq;
import com.romotc.scache.mgr;

public class QQUrlWatcherConfigService {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		List<QQUrlWatcherConfig> list = getAllConfigs();
		for(QQUrlWatcherConfig c : list)
		{
			System.out.println(c.getUrl());
		}

	}
	
	public static List<QQUrlWatcherConfig> getAllConfigs() {
		List<QQUrlWatcherConfig> configs = loadConfigDB();
		
		//将拦截器和Log按照processOrder排序 使他们按照数据库配置顺序执行
		Collections.sort(configs, new Comparator() {

			@Override
			public int compare(Object arg0, Object arg1) {
				QQUrlWatcherConfig config1 = (QQUrlWatcherConfig)arg0;
				QQUrlWatcherConfig config2 = (QQUrlWatcherConfig)arg1;
				//processOrder 小的 先执行
				return config1.getProcessOrder() - config2.getProcessOrder();
			}
			
		});
		
		return configs;
	}
	
	/**
	 * 从数据库或者文件配置中取配置
	 * @return
	 */
	private static List<QQUrlWatcherConfig> loadConfigDB() {
		QQUrlWatcherConfig urlConfig = new QQUrlWatcherConfig();
		
		List<QQUrlWatcherConfig> configs = null;
		
		//从数据库里加载
		if(false)
		try {
			int configSize = urlConfig.TotalCount();
			configs = (List<QQUrlWatcherConfig>)urlConfig.List(1, configSize);
		} catch (Exception e) {
			System.err.println("loadConfigDB from mysql error");
		}
		
		if(configs == null)
			configs = new ArrayList<QQUrlWatcherConfig>();
		
		
		//load from txt
		String path = "D:\\romotc\\dev\\scache-0.94\\conifg\\RequestSpyConfig.txt";
		try {
			List<String> txtLines = FileUtils.readLines(new File(path));
			configs.addAll(parseTxt(txtLines));
		} catch (IOException e) {
			System.err.println("loadConfigDB from txt error");
		}
		return configs;
	}

	private static Collection<? extends QQUrlWatcherConfig> parseTxt(
			List<String> txtLines) {
		List<QQUrlWatcherConfig> list = new ArrayList<QQUrlWatcherConfig>();
		
		ObjectMapper objMaper = Jackson.getObjectMaper();
		QQUrlWatcherConfig config;
		if(txtLines != null && !txtLines.isEmpty()) {
			for(String line : txtLines) {
				try {
					config = objMaper.readValue(line, QQUrlWatcherConfig.class);
					if(config != null)
						list.add(config);
				} catch (Exception e) {
					System.err.println("解析单个QQUrlWatcherConfig line异常");;
				} 
			}
		}
		
		
		return list;
	}

	public static QQUrlWatcherConfig getConfigByUrl(String url, List<QQUrlWatcherConfig> configs) {
		if(configs == null)
			configs = getAllConfigs();
		
		if(configs == null || configs.size() == 0 || url == null || "".equals(url.trim())) {
			return null;
		}
		
		QQUrlWatcherConfig defaultConfig = null;
		
		for(QQUrlWatcherConfig config : configs) {
			if(config.getUrl() != null) 
				if(mgr.simpleWildMatch(config.getUrl(), url) != null)
					if(!config.getUrl().equals("*"))
						return config;
					else
						defaultConfig = config;
		}
		
		return defaultConfig;
	}

	/**
	 * 检查合并文件配置与数据库配置，如果有冲突以数据库配置为准
	 * 如果文件配置中有的数据库配置中没有则增加到数据库中
	 */
	public static void dbLogConfigChecker() {
		if(httpreq.logpatterns == null) {
			return;
		}
		
		List<QQUrlWatcherConfig> dbConfigs = getAllConfigs();
		if(dbConfigs == null || dbConfigs.size() == 0) {
			//数据库中没有数据 将文件中数据导入到数据库中
			
			for(int i = 0; i < httpreq.logpatterns.length;i++) {
				String logPattern = httpreq.logpatterns[i];
				String logFile = httpreq.logfilenames[i];
				String logLevel = httpreq.logLevels[i];
				
				QQUrlWatcherConfig config = new QQUrlWatcherConfig();
				config.setUrl(logPattern);
				config.setLogFileName(logFile);
				config.setLogLevel(Integer.valueOf(logLevel));
				config.Save();
			}
		}else {
			//数据库中有数据 将数据库中数据写到httpreq对象中
			int size = dbConfigs.size();
			String[] logpatterns = new String[size]; 
			String[] logfilename = new String[size];
			String[] logLevels = new String[size];
			int i = 0;
			for(QQUrlWatcherConfig config : dbConfigs) {
				logpatterns[i] = config.getUrl();
				logfilename[i] = config.getLogFileName();
				logLevels[i++] = String.valueOf(config.getLogLevel());
			}
			
			httpreq.logpatterns = logpatterns;
			httpreq.logfilenames = logfilename;
			httpreq.logLevels = logLevels;
		}
	}

}
